var logger = require('../../lib/logger.lib');
var sha1 = require('../services/sha1.service');
var usersService = require('../services/users.service');
var pagesService = require('../services/pages.service');//查询单页信息渲染
var siteInfoService = require('../services/site-info.service');
var categoriesService = require('../services/categories.service');
var orderService = require('../services/order.service');
var async = require('async');

module.exports = {
    signin: function (req, res) {
        logger.system().info('登陆函数入口');
        req.checkBody({
            'account': {
                notEmpty: {
                    options: [true],
                    errorMessage: 'account 不能为空'
                }
            },
            'password': {
                notEmpty: {
                    options: [true],
                    errorMessage: 'password 不能为空'
                },
                isLength: {
                    options: [6],
                    errorMessage: 'password 不能小于 6 位'
                }
            }
        });
        logger.system().info('登陆函数检查完毕');

        var account = req.body.account;
        var password = req.body.password;
        var autoSignIn = true;

        if (req.validationErrors()) {
            logger.system().error(__filename, '参数验证失败', req.validationErrors());
            return res.status(400).end();
        }
        var isPhoneNumber = /^1[3|4|5|8][0-9]\d{8}$/.test(account);
        // var isEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(account);
        var query = { selectPassword: true };
        if (isPhoneNumber) {
            query.PhoneNumber = account;
        }
        else {
            query.email = account;
        }

        usersService.one(query, function (err, user) {
            if (err) {
                logger[err.type]().error(__filename, err);
                return res.status(500).end();
            }

            if (user && sha1(password) === user.password) {
                req.session.user = user._id;
                if (autoSignIn) req.session.cookie.maxAge = 60 * 1000 * 60 * 24 * 90;
                logger.system().info('登录完成');

                if (req.session.requestedPage) {
                    var target = req.session.requestedPage;
                    delete req.session.requestedPage;
                    return res.redirect(target);
                }
                else {
                    return res.redirect("/hyfw/hyxx");
                    // pagesService.one({
                    //     path: '/hyfw/hyxx'
                    // }, function (err, page) {
                    //     logger.system().info('进入回调');
                    //     if (err) return res.status(500).end();

                    //     if (!page) return next();
                    //     logger.system().info('开始异步渲染页面');
                    //     // //查询订单
                    //     // orderService.one({ user: user }, function (ordercallback) {
                    //     //     // 读取单页所需数据
                    //     //     async.parallel({
                    //     //         siteInfo: siteInfoService.get,
                    //     //         navigation: function (callback) {
                    //     //             categoriesService.navigation({ current: page.path }, callback);
                    //     //         },
                    //     //         order: ordercallback
                    //     //     }, function (err, results) {
                    //     //       return  res.render(page.views.page, {
                    //     //             layout: page.views.layout,
                    //     //             siteInfo: results.siteInfo,
                    //     //             navigation: results.navigation,
                    //     //             category: page,
                    //     //             content: page.mixed.pageContent,
                    //     //             media: page.mixed.pageMedia,
                    //     //             order: results.order
                    //     //             // user: user
                    //     //         });
                    //     //         //res.status(200).json(user)
                    //     //     });
                    //     // })
                    //     async.parallel({
                    //         siteInfo: siteInfoService.get,
                    //         navigation: function (callback) {
                    //             categoriesService.navigation({ current: page.path }, callback);
                    //         },
                    //         //order: ordercallback
                    //     }, function (err, results) {
                    //         return res.render(page.views.page, {
                    //             layout: page.views.layout,
                    //             siteInfo: results.siteInfo,
                    //             navigation: results.navigation,
                    //             category: page,
                    //             content: page.mixed.pageContent,
                    //             media: page.mixed.pageMedia,
                    //             order: results.order
                    //             // user: user
                    //         });
                    //         //res.status(200).json(user)
                    //     });
                    // });
                }
            } else {
                return res.status(401).json({
                    error: {
                        code: 'WRONG_EMAIL_OR_PASSWORD',
                        message: '用户名或密码错误'
                    }
                });
            }
        });
    }
}